package com.tbm.console.proj.json;

import com.alibaba.fastjson.JSONArray;
import com.tbm.console.base.controller.BaseController;
import com.tbm.console.common.constant.ConsoleConstant;
import com.tbm.console.common.constant.Controller2FTLConstant;
import com.tbm.console.common.constant.InsUpdDelFlagConstant;
import com.tbm.console.proj.entity.LocalLog;
import com.tbm.console.proj.entity.SystemImage;
import com.tbm.console.proj.entity.SystemMenu;
import com.tbm.console.proj.entity.SystemUser;
import com.tbm.console.proj.service.LocalLogService;
import com.tbm.console.proj.service.SystemImagesService;
import com.tbm.console.proj.service.SystemUserService;
import com.tbm.console.proj.view.SystemButtonMenuView;
import com.tbm.console.proj.ws.WebSocketServer;
import com.tbm.console.util.DateUtil;
import com.tbm.console.util.JsonUtils;
import com.tbm.console.util.PageData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class LocalLogJson extends BaseController {

    @Autowired
    private LocalLogService localLogService;

    @Autowired
    private SystemImagesService systemImagesService;

    @Autowired
    private SystemUserService systemUserService;


    /**
     * 日志的新增和修改
     * 如果id==-1，表示新增
     * @param
     * @return
     */
    @RequestMapping(value = "/log-ins-upd-del")
    public Object logCreateUpdate(){
        PageData pageData = this.getPageData();
        Integer id = -1;
        if(null != pageData.get("id")&&!"".equals(pageData.get("id").toString())){
            id = Integer.valueOf(pageData.get("id").toString());
        }
        LocalLog localLog = localLogService.findById(id);
        //------------------------------------------------------- 新增修改操作 ----------------------------------------------------------------------//
        if(-1==id){
            localLog.setCreateTime(DateUtil.getTime());
            SystemUser systemUser = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(), SystemUser.class);
            localLog.setLogCommitter(systemUser.getNickname());
            localLog.setLogCommitterId(String.valueOf(systemUser.getId()));
        }else{
            localLog.setUpdateTime(DateUtil.getTime());
        }

        //日志名称字段信息维护
        if(null!=pageData.get("logTitle")&&!"".equals(pageData.get("logTitle").toString())){
            localLog.setLogTitle(pageData.get("logTitle").toString());
        }
        //日志描述字段信息维护
        if(null!=pageData.get("logDescription")&&!"".equals(pageData.get("logDescription").toString())){
            localLog.setLogDescription(pageData.get("logDescription").toString());
        }
        //日志类型字段信息维护
        if(null!=pageData.get("logType")&&!"".equals(pageData.get("logType").toString())){
            localLog.setLogType(pageData.get("logType").toString());
        }
        //工作量字段信息维护
        if(null!=pageData.get("logWorkload")&&!"".equals(pageData.get("logWorkload").toString())){
            localLog.setLogWorkload(Double.valueOf(pageData.get("logWorkload").toString()));
        }

        //------------------------------------------------------- 删除操作 ---------------------------------------------------------------------------//
        if(null!=pageData.get("flag")&&"Y".equals(pageData.get("flag").toString())){
            localLog.setDeleteFlag(pageData.get("flag").toString());
        }
        //------------------------------------------------------- 添加日志详细信息操作 ----------------------------------------------------------------//
        if(null!=pageData.get("flag")&&"D".equals(pageData.get("flag").toString())){
            localLog.setLogContent(pageData.get("content").toString());
        }
        //------------------------------------------------------- 推送日志详细信息操作 ----------------------------------------------------------------//
        if(null!=pageData.get("flag")&&"P".equals(pageData.get("flag").toString())){
            localLog.setUploadFlag(localLog.getUploadFlag().equals("P")?InsUpdDelFlagConstant.LOCALLOGNOTPUSHFLAG:InsUpdDelFlagConstant.LOCALLOGPUSHFLAG);
        }
        localLogService.save(localLog);
        //-------------------------------------------------------------WebSocket推送提示---------------------------------------------------------------//
        if(null!=pageData.get("flag")&&"P".equals(pageData.get("flag").toString())){
            try {
                WebSocketServer.sendInfo("1");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/log-list/{page}/{size}")
    public Map<String,Object> localLogList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageData pageData = this.getPageData();
        //获取用户
        PageData param = new PageData();
        param.put("deleteFlag", "N");
        //------------------------------------搜索-----------------------------------------------------------------//
        if(null!=pageData.get("system")&&!"".equals(pageData.get("system"))){
            param.put("system", pageData.get("system").toString());
        }
        if(null!=pageData.get("desc")&&!"".equals(pageData.get("desc").toString())){
            param.put("desc", pageData.get("desc").toString());
        }
        if(null!=pageData.get("log")&&!"".equals(pageData.get("log").toString())){
            param.put("log", pageData.get("log").toString());
        }

        //查出所有的数据
        List<LocalLog> localLogs = localLogService.findAll(param,page-1,size);

        //------------------------------------搜索-----------------------------------------------------------------//
        SystemUser loginUser = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(), SystemUser.class);

        String belongTo = loginUser.getBelongTo();
        String powerLevel = loginUser.getPowerLevel();
        //如果是班组长
        List<LocalLog> result = new ArrayList<>();
        if(powerLevel.equals(ConsoleConstant.POWERLEVELGROUPERMANAGER)){
            PageData systemPd = new PageData();
            systemPd.put("belongTo", belongTo);
            List<SystemUser> all = systemUserService.findAll(systemPd);
            for(LocalLog ll:localLogs){
                for(SystemUser user : all){
                    if(ll.getLogCommitterId().equals(String.valueOf(user.getId()))){
                        ll.setBelongToBusinessUnit(user.getBelongTo());
                        result.add(ll);
                    }
                }
            }
        }
        //如果是组员
        else if(powerLevel.equals(ConsoleConstant.POWERLEVELGROUPER)){
            for(LocalLog ll:localLogs){
                if(ll.getLogCommitterId().equals(String.valueOf(loginUser.getId()))){
                    ll.setBelongToBusinessUnit(belongTo);
                    result.add(ll);
                }
            }
        }
        //如果是主任
        else{
            List<SystemUser> all = systemUserService.findAll();
            for(LocalLog ll:localLogs){
                for(SystemUser user : all){
                    if(ll.getLogCommitterId().equals(String.valueOf(user.getId()))){
                        ll.setBelongToBusinessUnit(user.getBelongTo());
                        result.add(ll);
                    }
                }
            }
        }

        long count = result.size();
        //目前未找到优雅的方式来统计工作量，只能循环来求和
        Double init = new Double(0);
        for(LocalLog localLog:result){
            //存在精度问题
            init += localLog.getLogWorkload();
        }
        List<PageData> footer = new ArrayList<>();
        PageData p1 = new PageData();
        p1.put("logDescription", "工作量统计");
        p1.put("logWorkload", new BigDecimal(init).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue()+"人天");
        footer.add(p1);
        pageData.put("total",count);
        pageData.put("rows", result);
        pageData.put("footer", footer);
        return pageData;
    }

    /**
     * 判断log是否含有上传图片
     * @param id
     * @return
     */
    @RequestMapping(value = "/log-has-images/{id}")
    public String logHasImages(@PathVariable("id") Integer id){
        PageData pageData = new PageData();
        pageData.put("userId", id);
        List<SystemImage> imagesEntityList = systemImagesService.findAll(pageData);
        if (0==imagesEntityList.size()){
            return ConsoleConstant.ZERO;
        }else{
            return ConsoleConstant.HAS;
        }
    }



}
